// ==========================================================================
// GFast自动生成logic操作代码。
// 生成日期：2024-01-05 17:57:11
// 生成路径: internal/app/flow/logic/flow_model.go
// 生成人：gfast
// desc:流程模型
// company:云南奇讯科技有限公司
// ==========================================================================

package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/tiger1103/gfast/v3/internal/app/flow/consts"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/tiger1103/gfast/v3/internal/app/flow/dao"
	"github.com/tiger1103/gfast/v3/internal/app/flow/model"
	"github.com/tiger1103/gfast/v3/internal/app/flow/model/do"
	"github.com/tiger1103/gfast/v3/internal/app/flow/service"
	systemConsts "github.com/tiger1103/gfast/v3/internal/app/system/consts"
	systemService "github.com/tiger1103/gfast/v3/internal/app/system/service"
	"github.com/tiger1103/gfast/v3/library/liberr"
	"github.com/xuri/excelize/v2"
)

func init() {
	service.RegisterFlowModel(New())
}

func New() service.IFlowModel {
	return &sFlowModel{}
}

type sFlowModel struct{}

func (s *sFlowModel) List(ctx context.Context, req *model.FlowModelSearchReq) (listRes *model.FlowModelSearchRes, err error) {
	listRes = new(model.FlowModelSearchRes)
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.FlowModel.Ctx(ctx).WithAll()
		if req.Name != "" {
			m = m.Where(dao.FlowModel.Columns().Name+" like ?", "%"+req.Name+"%")
		}
		if req.FlowType != "" {
			m = m.Where(dao.FlowModel.Columns().FlowType+" = ?", gconv.Int(req.FlowType))
		}
		if req.FlowFormCate != "" {
			m = m.Where(dao.FlowModel.Columns().FlowFormCate+" = ?", gconv.Int64(req.FlowFormCate))
		}
		if req.FlowBusinessCate != "" {
			m = m.Where(dao.FlowModel.Columns().FlowBusinessCate+" = ?", req.FlowBusinessCate)
		}
		if req.Sort != "" {
			m = m.Where(dao.FlowModel.Columns().Sort+" = ?", gconv.Int64(req.Sort))
		}
		if req.Status != "" {
			m = m.Where(dao.FlowModel.Columns().Status+" = ?", gconv.Int(req.Status))
		}
		listRes.Total, err = m.Count()
		liberr.ErrIsNil(ctx, err, "获取总行数失败")
		if req.PageNum == 0 {
			req.PageNum = 1
		}
		listRes.CurrentPage = req.PageNum
		if req.PageSize == 0 {
			req.PageSize = systemConsts.PageSize
		}
		order := "id desc"
		if req.OrderBy != "" {
			order = req.OrderBy
		}
		var res []*model.FlowModelListRes
		err = m.Page(req.PageNum, req.PageSize).Order(order).Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
		listRes.List = make([]*model.FlowModelListRes, len(res))
		for k, v := range res {
			listRes.List[k] = &model.FlowModelListRes{
				Id:                 v.Id,
				Name:               v.Name,
				FlowType:           v.FlowType,
				FlowFormCate:       v.FlowFormCate,
				LinkedFlowFormCate: v.LinkedFlowFormCate,
				FlowBusinessCate:   v.FlowBusinessCate,
				Status:             v.Status,
				CreatedAt:          v.CreatedAt,
				CreatedUser:        v.CreatedUser,
				CreatedBy:          v.CreatedBy,
			}
		}
	})
	return
}

func (s *sFlowModel) GetExportData(ctx context.Context, req *model.FlowModelSearchReq) (listRes []*model.FlowModelInfoRes, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.FlowModel.Ctx(ctx).WithAll()
		if req.Name != "" {
			m = m.Where(dao.FlowModel.Columns().Name+" like ?", "%"+req.Name+"%")
		}
		if req.FlowType != "" {
			m = m.Where(dao.FlowModel.Columns().FlowType+" = ?", gconv.Int(req.FlowType))
		}
		if req.FlowFormCate != "" {
			m = m.Where(dao.FlowModel.Columns().FlowFormCate+" = ?", gconv.Int64(req.FlowFormCate))
		}
		if req.FlowBusinessCate != "" {
			m = m.Where(dao.FlowModel.Columns().FlowBusinessCate+" = ?", req.FlowBusinessCate)
		}
		if req.Sort != "" {
			m = m.Where(dao.FlowModel.Columns().Sort+" = ?", gconv.Int64(req.Sort))
		}
		if req.Status != "" {
			m = m.Where(dao.FlowModel.Columns().Status+" = ?", gconv.Int(req.Status))
		}
		if req.PageNum == 0 {
			req.PageNum = 1
		}
		if req.PageSize == 0 {
			req.PageSize = systemConsts.PageSize
		}
		order := "id desc"
		if req.OrderBy != "" {
			order = req.OrderBy
		}
		err = m.Page(req.PageNum, req.PageSize).Order(order).Scan(&listRes)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
	})
	return
}

func (s *sFlowModel) Import(ctx context.Context, file *ghttp.UploadFile) (err error) {
	if file == nil {
		err = errors.New("请上传数据文件")
		return
	}
	var data []do.FlowModel
	err = g.Try(ctx, func(ctx context.Context) {
		f, err := file.Open()
		liberr.ErrIsNil(ctx, err)
		defer f.Close()
		exFile, err := excelize.OpenReader(f)
		liberr.ErrIsNil(ctx, err)
		defer exFile.Close()
		rows, err := exFile.GetRows("Sheet1")
		liberr.ErrIsNil(ctx, err)
		if len(rows) == 0 {
			liberr.ErrIsNil(ctx, errors.New("表格内容不能为空"))
		}
		d := make([]interface{}, len(rows[0]))
		data = make([]do.FlowModel, len(rows)-1)
		for k, v := range rows {
			if k == 0 {
				continue
			}
			for kv, vv := range v {
				d[kv] = vv
			}
			data[k-1] = do.FlowModel{
				Name:             d[0],
				FlowType:         gconv.Int64(d[1]),
				FlowFormCate:     gconv.Int64(d[2]),
				Remark:           d[3],
				FlowBusinessCate: d[4],
				Sort:             gconv.Int64(d[5]),
				Status:           gconv.Int64(d[6]),
				CreatedAt:        gconv.GTime(d[7]),
				UpdatedAt:        gconv.GTime(d[8]),
				DeletedAt:        gconv.GTime(d[9]),
				CreatedBy:        gconv.Int64(d[10]),
				UpdatedBy:        gconv.Int64(d[11]),
			}
		}
		if len(data) > 0 {
			err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
				_, err = dao.FlowModel.Ctx(ctx).Batch(500).Insert(data)
				return err
			})
			liberr.ErrIsNil(ctx, err)
		}
	})
	return
}

// LinkedDataSearch 相关连表查询数据
func (s *sFlowModel) LinkedFlowModelDataSearch(ctx context.Context) (res *model.LinkedFlowModelDataSearchRes, err error) {
	res = new(model.LinkedFlowModelDataSearchRes)
	res.LinkedFlowModelFlowForm, err = s.ListFlowModelFlowForm(ctx)
	liberr.ErrIsNil(ctx, err, "获取关联表信息失败")
	return
}

func (s *sFlowModel) GetById(ctx context.Context, id uint64) (res *model.FlowModelInfoRes, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.FlowModel.Ctx(ctx).WithAll().Where(dao.FlowModel.Columns().Id, id).Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取信息失败")
	})
	return
}

func (s *sFlowModel) Add(ctx context.Context, req *model.FlowModelAddReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.FlowModel.Ctx(ctx).Insert(do.FlowModel{
			Name:             req.Name,
			FlowType:         req.FlowType,
			FlowFormCate:     req.FlowFormCate,
			Remark:           req.Remark,
			FlowBusinessCate: req.FlowBusinessCate,
			Sort:             req.Sort,
			Status:           req.Status,
			CreatedBy:        systemService.Context().GetUserId(ctx),
		})
		liberr.ErrIsNil(ctx, err, "添加失败")
	})
	return
}

func (s *sFlowModel) Edit(ctx context.Context, req *model.FlowModelEditReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.FlowModel.Ctx(ctx).WherePri(req.Id).Update(do.FlowModel{
			Name:             req.Name,
			FlowType:         req.FlowType,
			FlowFormCate:     req.FlowFormCate,
			Remark:           req.Remark,
			FlowBusinessCate: req.FlowBusinessCate,
			Sort:             req.Sort,
			Status:           req.Status,
			UpdatedBy:        systemService.Context().GetUserId(ctx),
		})
		liberr.ErrIsNil(ctx, err, "修改失败")
	})
	return
}

func (s *sFlowModel) Delete(ctx context.Context, ids []uint64) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.FlowModel.Ctx(ctx).Delete(dao.FlowModel.Columns().Id+" in (?)", ids)
		liberr.ErrIsNil(ctx, err, "删除失败")
	})
	return
}

func (s *sFlowModel) ListFlowModelFlowForm(ctx context.Context) (linkedFlowModelFlowForm []*model.LinkedFlowModelFlowForm, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.FlowForm.
			Ctx(ctx).
			Fields(model.LinkedFlowModelFlowForm{}).Scan(&linkedFlowModelFlowForm)
		liberr.ErrIsNil(ctx, err)
	})
	return
}

func (s *sFlowModel) SaveNodeInfo(ctx context.Context, modelId uint64, nodes []*model.FlowModelNodeAddReq, edges []*model.FlowNodeLineAddReq) (err error) {
	//检查流程基本配置是否正确
	startNum := 0 //起始节点数
	endNum := 0   //结束节点数

	for _, node := range nodes {
		if node.NodeType == consts.FlowNodeTypeStart {
			startNum++
		}
		if node.NodeType == consts.FlowNodeTypeEnd {
			endNum++
		}
	}
	if startNum == 0 {
		err = errors.New("没有设置起始节点，请修改。")
		return
	}
	if startNum > 1 {
		err = errors.New(fmt.Sprintf("有 %d 个起始节点，只能有一个，请修改！", startNum))
		return
	}
	if endNum == 0 {
		err = errors.New("至少需要有一个结束节点")
		return
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		err = g.Try(ctx, func(ctx context.Context) {
			//删除旧的节点相关信息
			_, err = dao.FlowModelNode.Ctx(ctx).Where(dao.FlowModelNode.Columns().ModelId, modelId).Delete()
			liberr.ErrIsNil(ctx, err, "删除旧节点信息失败")
			_, err = dao.FlowNodeLine.Ctx(ctx).Where(dao.FlowNodeLine.Columns().ModelId, modelId).Delete()
			liberr.ErrIsNil(ctx, err, "删除旧节点关联信息失败")
			_, err = dao.FlowModelNode.Ctx(ctx).Data(nodes).Insert()
			liberr.ErrIsNil(ctx, err, "保存节点信息失败")
			_, err = dao.FlowNodeLine.Ctx(ctx).Data(edges).Insert()
			liberr.ErrIsNil(ctx, err, "保存节点关联信息失败")
		})
		return err
	})
	return
}
func (s *sFlowModel) GetNodeInfo(ctx context.Context, modelId uint64) (nodeInfo *model.NodeInfoRes, err error) {
	nodeInfo = new(model.NodeInfoRes)
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.FlowModelNode.Ctx(ctx).Where(dao.FlowModelNode.Columns().ModelId, modelId).Scan(&nodeInfo.Nodes)
		liberr.ErrIsNil(ctx, err, "获取节点信息失败")
		err = dao.FlowNodeLine.Ctx(ctx).Where(dao.FlowNodeLine.Columns().ModelId, modelId).Scan(&nodeInfo.Edges)
		liberr.ErrIsNil(ctx, err, "获取节点关联信息失败")
	})
	return
}
